<?php
/*
 * 合同控制器
*/
header("Content-Type: text/html;charset=UTF-8");
class Contract extends CI_Controller {
	function __construct() {
		parent::__construct ();
		$this->load->helper ( 'url' );
		$this->load->library ( 'pagination' );
		$this->load->helper(array('form', 'url'));
	}

	public function index($offset = '') {
		$user_name=$this->session->userdata('username');
		if($user_name){
			$this->load->model ( 'contract_model', 'contactm' );
			$limit = 10;
			$total = $this->contactm->count_nums ();
			$data['total']=$total;
			$data['offset']=$offset;
			$data ['contract'] = $this->contactm->list_contracters ( $limit, $offset );
			$current_total=count($data ['contract']);
			$data['current_total']=$offset+$current_total;
			
			$config ['base_url'] = base_url () . 'index.php/contract/index/';
			$config ['total_rows'] = $total;
			$config ['per_page'] = $limit;
			$config ['num_links'] = 4;
			$config ['first_link'] = '首页';
			$config ['last_link'] = '尾页';
			$this->pagination->initialize ( $config );
			$data ['pag_links'] = $this->pagination->create_links ();
			
			$data ['page_title'] = '合同/订单 — 昊美科技CRM系统';
			$data ['class4'] = 'cur';
			$data ['all_users'] = $this->get_all_users();
			$this->load->view ( 'contract_list', $data );
		}else{
			$this->load->view ( 'login');
		}
	}
	
	/*
	 * 客户名查询记录
	*/
	public function check($name = ''){
		$this->db->select('customer.customer_name as customer_name,contract.*,opportunity.id as opportunity_id,user.user_name as user_name')->from('customer')->join('contract', 'contract.customer_id = customer.id')->join('opportunity', 'contract.opportunity_id = opportunity.id')->join('user','contract.owner_id=user.id')->like('contract.subject',urldecode($name))->order_by('contract.signing_time', "desc");
		$query = $this->db->get();
		$data['contract'] = $query->result();
		$data ['pag_links'] = '';
		$data ['page_title'] = '合同/订单 — 昊美科技CRM系统';
		$data ['class4'] = 'cur';
		$this->load->view ( 'contract_list', $data );
	}
	
	/**
	 * 数据所有者查询
	 * */
	public function check_user_messages($id = ''){
		$data['contract'] = $this->list_user_contracters($id);
		$data ['pag_links'] = '';
		$data ['page_title'] = '销售机会 — 昊美科技CRM系统';
		$data ['class4'] = 'cur';
		$data ['all_users'] = $this->get_all_users();
		$query = $this->db->query('SELECT user_name FROM user where id = '.$id.'');
		$row = $query->row();
		$data ['check_user_name'] = $row->user_name;
		$this->load->view ( 'contract_list', $data );
	}
	
	/*
	 * 查看某条记录
	*/
	public function find($id = '') {
		$data = $this->check_find($id);
		$this->load->view ( 'contract_view',$data);
	}
	
	public function console_find_contract(){
		$data = $this->check_find($id);
		$this->load->view ( 'console_contract_view',$data);
	}
	
	public function check_find($id = ''){
		$this->db->select('customer.customer_name as customer_name,contract.*,opportunity.id as opportunity_id,opportunity.subject as opportunity_subject,user.user_name as user_name')->from('customer')->join('contract', 'contract.customer_id = customer.id')->join('opportunity', 'contract.opportunity_id = opportunity.id')->join('user','contract.owner_id=user.id')->where('contract.contract_id',$id);
		$query = $this->db->get();
		$data['find_contract'] = $query->result();
		
		/*查询该份合同的回款记录*/
		$query = $this->db->query("SELECT * FROM payment_record where contract_id = $id");
		$data['payment_records']=$query->result();
		return $data;
	}
	
	/*
	 * 删除记录
	*/
	public function delete($id = '') {
		$role=$this->session->userdata('role');
		if($role == '经理'){
			$this->db->delete ( 'contract', array ('contract_id' => $id ) );
		}
		redirect ( 'contract/index/' );
	}

	/*
	 * 查看某条编辑记录
	*/
	public function edit($id = '') {
		$this->db->select('customer.customer_name as customer_name,customer.id as customer_id,contract.*,opportunity.id as opportunity_id,opportunity.subject as opportunity_subject,user.id as user_id,user.user_name as user_name')->from('customer')->join('contract', 'contract.customer_id = customer.id')->join('opportunity', 'contract.opportunity_id = opportunity.id')->join('user','contract.owner_id=user.id')->where('contract.contract_id',$id);
		$query = $this->db->get();
		$data['update_contract'] = $query->row();
		/*查询该份合同的回款记录*/
		$query = $this->db->query("SELECT * FROM payment_record where contract_id = $id");
		$data['payment_records']=$query->result();
		$data ['all_users'] = $this->get_all_users();
		$this->load->view ( 'contract_edit', $data );
	}

	/*
	 * 新增客户
	*/
	public function show_contract_add($customer_name = '',$id = ''){ /*显示增加页面*/
		$data ['all_users'] = $this->get_all_users();
		$data ['customer_name'] = urldecode($customer_name);
		
		if($id){
			/*获取对应客户的销售机会*/
			$query = $this->db->query('SELECT id,subject FROM opportunity where customer_id = '.$id.'');
			$opportunity = $query->result();
			$count = count($opportunity);
			for($i=0;$i<$count;$i++){
				$opp_id = $opportunity[$i]->id;
				$query = $this->db->query('SELECT count(*) as nums FROM contract where opportunity_id = '.$opp_id.'');
				$row = $query->row_array();
				if($row['nums']){
					unset($opportunity[$i]);
				}
			}
			$data ['oppes'] = $opportunity;
		}
		
		$this->load->view ( 'contract_add',$data);
	}

	public function insert(){
		$data_array = $_POST;
		
		/*上传文件*/
		$filerepository = getcwd()."/upload/";
		if(!is_dir($filerepository)){ /*判断给定文件名是否是一个目录*/
			mkdir ($filerepository);
		}
		$config['upload_path'] = $filerepository;
		$config['allowed_types'] = 'gif|jpg|png|txt|xlsx|docx|xls|doc';
		$config['max_size'] = '20480';
		$config['max_width']  = '20480';
		$config['max_height']  = '20480';
		$config['overwrite']  = false;
		$config['encrypt_name']  = true;
		
		$this->load->library('upload', $config);
		if($data_array['textfield'] != ''){
			if ( (! $this->upload->do_upload())){
				$this->load->view ( 'update_error');
			}else{
				$data = array('upload_data' => $this->upload->data());
				$file_name = $data['upload_data']['file_name'];/*加密名*/
				$client_name = $data['upload_data']['client_name']; /*客户端文件名*/
				/*保存数据*/
				$data_array = $_POST;
				$data_array['text_attachments'] = $file_name;
				$data_array['real_file_name'] = $client_name;
			}
		}
		unset($data_array['textfield']);
		/*
		 * 获取客户编号,联系人编号,拥有者编号
		*/
		$customer_id = '';
		$owner_id = '';
		$this->db->select ( 'id' )->from ( 'customer' )->where ( 'customer_name', $data_array ['customer_name'] );
		$query = $this->db->get ()->result ();
		$customer_id = $query[0]->id;
			
		$this->db->select ( 'id' )->from ( 'user' )->where ( 'user_name', $data_array ['owner_name'] );
		$query = $this->db->get ()->result ();
		$owner_id = $query[0]->id; /*拥有者id*/
			
		$data_array ['customer_id']=$customer_id;
		$data_array ['owner_id']=$owner_id;
		unset($data_array ['customer_name']);
		unset($data_array ['opportunity_subject']);
		unset($data_array ['owner_name']);
			
		date_default_timezone_set ( 'PRC' );
		$now_time = date ( 'Y-m-d H:i:s', strtotime ( 'now' ) );
		$data_array ['create_time'] = $now_time;
		
		$q=$this->db->insert('contract', $data_array);
		if($q > 0){
			redirect ( 'contract/index/' );
		}else{
			$data = array('upload_data' => $this->upload->data());
			$file_name = $data['upload_data']['file_name'];/*加密名*/
			$client_name = $data['upload_data']['client_name']; /*客户端文件名*/
		}
	}

	/*
	 * 编辑某条纪律
	*/
	public function update() {
		/*上传文件*/
		$filerepository = getcwd()."/upload/";
		$agofilerepository = getcwd()."/ago_upload/";
		if(!is_dir($filerepository)){ /*判断给定文件名是否是一个目录*/
			mkdir ($filerepository);
		}
		if(!is_dir($agofilerepository)){ 
			mkdir ($agofilerepository);
		}
		$config['upload_path'] = $filerepository;
		$config['allowed_types'] = 'pdf|gif|jpg|png|txt|xlsx|docx|xls|doc';
		$config['max_size'] = '20480';
		$config['max_width']  = '20480';
		$config['max_height']  = '20480';
		$config['overwrite']  = false;
		$config['encrypt_name']  = true;
		
		$this->load->library('upload', $config);
		$data_array = $_POST;
		if($data_array['textfield'] != ''){
			if ( ! $this->upload->do_upload()){ /*上传失败*/
				//$error = array('error' => $this->upload->display_errors());
				$data_array['text_attachments'] = $data_array['hitext'];
				$data_array['real_file_name'] = $data_array['hireal'];
				unset($data_array['hitext']);
				unset($data_array['hireal']);
				$this->load->view ( 'update_error');
			}else{
				$data = array('upload_data' => $this->upload->data());
			
				$contract_id = $data_array['contract_id'];
				$query = $this->db->query("SELECT text_attachments FROM contract where contract_id = $contract_id");
				$row = $query->row_array();
				$text_attachments=$row['text_attachments'];/*获取加密名*/
					
				if($text_attachments){
					if(file_exists($filerepository.$text_attachments)){ /*检查文件或目录是否存在*/
						if(!rename($filerepository.$text_attachments,$agofilerepository.$text_attachments)){ /*移动文件失败*/
							redirect ( 'contract/index/' );
						}
					}else{
						//echo '源文件未找到';
					}
				}
				$file_name = $data['upload_data']['file_name'];/*加密名*/
				$client_name = $data['upload_data']['client_name']; /*客户端文件名*/
					
				$data_array['text_attachments'] = $file_name;
				$data_array['real_file_name'] = $client_name;
					
			}	
		}
		unset($data_array['hitext']);
		unset($data_array['hireal']);
		unset($data_array['textfield']);
		$contract_id = $data_array['contract_id'];
		$customer_id='';$user_id='';
		if($data_array['customer_name'] != $data_array['hicuname']){ /*获取客户编号*/
			$this->db->select ( 'id' )->from ( 'customer' )->where ( 'customer_name', $data_array ['customer_name'] );
			$query = $this->db->get ();
			foreach ( $query->result () as $rows ) {
				$customer_id = $rows->id;
			}
			$data_array['customer_id']=$customer_id;
		}
			
		if($data_array['hiusname'] != $data_array['user_name']){ /*获取用户编号*/
			$this->db->select ( 'id' )->from ( 'user' )->where ( 'user_name', $data_array ['user_name'] );
			$query = $this->db->get ();
			foreach ( $query->result () as $rows ) {
				$user_id = $rows->id;
			}
			$data_array['owner_id']=$user_id;
		}
			
		unset($data_array['contract_id']);
		unset($data_array['customer_name']);
		unset($data_array['hiusname']);
		unset($data_array['hicuname']);
		unset($data_array['hiusid']);
		unset($data_array['user_name']);
			
		$this->db->where('contract_id', $contract_id);
		$row=$this->db->update('contract', $data_array);
		if($row > 0){
			redirect ( 'contract/index/' );
		}else{
		}
		
	}

	/*查询对应机会*/
	public function check_opportunity(){
		$data_array = $_POST;
		/*获取对应客户编号*/
		$this->db->select ( 'id' )->from ( 'customer' )->where ( 'customer_name', $data_array ['name'] );
		$query = $this->db->get ();
		$row = $query->row();
		$customer_id = $row->id;
		/*获取客户对应的销售机会*/
		$this->db->select ( 'id' )->from ( 'opportunity' )->where ( 'customer_id', $customer_id );
		$query = $this->db->get ();
		$data_array = array();
		foreach ($query->result() as $row){
			$opp_id = $row->id;
			$query = $this->db->query("SELECT count(*) as nums,opportunity_id FROM opportunity_stage where opportunity_id = $opp_id and stage in ('沟通','招投标/谈判','立项','签合同')");
			$row = $query->row_array();
			$nums = $row['nums'];
			
			/*检测是否添加过合同*/
			$q_contract = $this->db->query('SELECT count(*) as contract_nums FROM contract where opportunity_id = '.$opp_id.'');
			$row_contract = $q_contract->row_array();
			$contract_nums = $row_contract['contract_nums'];
			if($nums >=1 && $contract_nums == 0){ /*满足一项阶段条件即可创建合同*/
				$opp_id = $row['opportunity_id'];
				$this->db->select ( 'id,subject' )->from ( 'opportunity' )->where ( 'id', $opp_id );
				$query = $this->db->get ();
				$opportunity_array = $query->result_array();
				$data_array[] = $opportunity_array;
			}
		}
		$json_string = json_encode($data_array);
		echo $json_string;
	}

	/*自动搜索获取合同*/
	public function get_contract(){
		$data_array = $_POST;
		/*获取对应客户编号*/
		$this->db->select ( 'id' )->from ( 'customer' )->where ( 'customer_name', $data_array ['name'] );
		$query = $this->db->get ();
		$row = $query->row();
		$customer_id = $row->id;

		$this->db->select ( 'contract_id,subject' )->from ( 'contract' )->where ( 'customer_id', $customer_id );
		$query = $this->db->get ();
		$opportunity_array = $query->result_array();
		$opportunity_array2 = $opportunity_array;
		if(!$data_array['type_record']){
			for($m=0;$m<count($opportunity_array);$m++){
				$q = $this->db->query('SELECT count(*) as nums FROM payment_plan where contract_id = '.$opportunity_array[$m]['contract_id'].'');
				$row = $q->row();
				if($row->nums > 0){
					unset($opportunity_array2[$m]); /*删除已有回款计划的合同*/
				}
			}
		}else{
			for($n=0;$n<count($opportunity_array);$n++){
				$q = $this->db->query('SELECT count(*) as nums FROM payment_plan where contract_id = '.$opportunity_array[$n]['contract_id'].'');
				$row = $q->row();
				$plan_nums = $row->nums;
				
				$q = $this->db->query('SELECT money FROM payment_plan where contract_id = '.$opportunity_array[$n]['contract_id'].'');
				$row = $q->row();
				$plan_money = $row->money; /*计划回款金额*/
				
				$q = $this->db->query('SELECT money FROM payment_record where contract_id = '.$opportunity_array[$n]['contract_id'].'');
				$total_record_money='';
				foreach ($q->result() as $row){
					$total_record_money = $total_record_money + $row->money;
				}
				
				$q = $this->db->query('SELECT count(*) as nums FROM payment_record where contract_id = '.$opportunity_array[$n]['contract_id'].'');
				$row = $q->row();
				$real_stages = $row->nums;
				$q = $this->db->query('SELECT stages FROM payment_plan where contract_id = '.$opportunity_array[$n]['contract_id'].'');
				$row = $q->row();
				$total_stages = $row->stages;
				
				if($plan_nums <= 0 || ($plan_money == $total_record_money && $real_stages == $total_stages)){
					unset($opportunity_array2[$n]); 
				}
			}
		}
		
		$json_string = json_encode($opportunity_array2);
		echo $json_string;
	}
	
	/*下载附件*/
	public function download($id = ''){
		$query = $this->db->query("SELECT text_attachments,real_file_name FROM contract where contract_id = $id");
		$row = $query->row();
		$file_name=$row->text_attachments;
		$real_file_name=$row->real_file_name;
		
		$this->load->helper('download');
		$filerepository = getcwd()."/upload/";
		if(!file_exists($filerepository.$file_name)){
			echo '源文件未找到';
		}else{
			$data = file_get_contents($filerepository.$file_name); // 读文件内容
			$name = $real_file_name;
			force_download($name, $data);
		}
	}
	
	/*合同编号唯一性检测*/
	public function check_contract_number(){
		$data_array = $_POST;
		$query = $this->db->query("SELECT count(*) as nums FROM contract where contract_no = '".$data_array['number']."'");
		$row = $query->row();
		$nums = $row->nums;
		if($nums){
			echo $nums;
		}else{
			echo '';
		}
	}
	/*获取所有用户*/
	public function get_all_users(){
		$query = $this->db->query("SELECT * FROM user order by create_time asc");
		return $query->result();
	}
	
	public function list_user_contracters($user_id = ''){ 
		$contracts = array();
		if($user_id == 0){
			redirect ( 'contract/index/' );
		}else{
			$query = $this->db->where(owner_id,$user_id)->from('contract')->order_by("create_time", "desc")->get();
			
			foreach($query->result() as $row) {
				$customer_query = $this->db->get_where ( 'customer',array ('id' => $row->customer_id), $condition_array );
				$customer = $customer_query->row();
				$row->customer_name = $customer->customer_name;
			
				$user_query = $this->db->get_where ( 'user', array ('id' => $row->owner_id ) );
				$user = $user_query->row();
				$row->user_name = $user->user_name;
			
				$contracts[] = $row;
			}
			return $contracts;
		}
	}
}
?>